<template>
    <div class="history-attendance">
        <el-tabs v-model="activeTab" @tab-click="onTabClick">
            <el-tab-pane label="今日考勤" name="today" />
            <el-tab-pane label="缺勤统计" name="absence" />
            <el-tab-pane label="历史考勤" name="history" />
            <el-tab-pane label="请假管理" name="leave" />
            <el-tab-pane label="离校管理" name="leaveSchool" />
            <el-tab-pane label="考勤时间设置" name="setting" />
        </el-tabs>
        <div class="filter-bar">
            <el-date-picker v-model="dateRange" type="daterange" range-separator="-" start-placeholder="开始日期"
                end-placeholder="结束日期" style="width: 260px; margin-right: 10px;" />
            <el-select v-model="className" placeholder="班级" style="width: 150px; margin-right: 10px;">
                <el-option v-for="item in classOptions" :key="item" :label="item" :value="item" />
            </el-select>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="handleReset" style="margin-left: 8px;">重置</el-button>
            <el-button type="success" @click="handleExport" style="margin-left: 8px;">导出数据</el-button>
        </div>
        <div class="result-info">查询结果：共计 {{ tableData.length }} 条数据</div>

        <!-- 历史考勤统计表 -->
        <el-table :data="tableData" border style="width: 100%; margin-top: 10px;" v-loading="loading">
            <el-table-column prop="className" label="班级" width="140" />
            <el-table-column prop="attendanceDays" label="考勤天数" width="100" align="center" />
            <el-table-column prop="totalAttendance" label="总人次数" width="100" align="center" />
            <el-table-column prop="actualAttendance" label="实到人次数" width="120" align="center" />
            <el-table-column prop="absenceCount" label="缺勤人次数" width="120" align="center" />
            <el-table-column prop="attendanceRate" label="出勤率" width="100" align="center" />
            <el-table-column label="操作" width="120">
                <template #default="scope">
                    <el-button type="primary" size="small" @click="viewDetail(scope.row)">详情</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 历史考勤详情弹窗 -->
        <el-dialog v-model="detailDialogVisible" title="历史考勤详情" width="80%" destroy-on-close>
            <div class="detail-filter">
                <el-date-picker v-model="detailDate" type="date" placeholder="选择日期"
                    style="width: 180px; margin-right: 10px;" />
                <el-select v-model="detailTimePeriod" placeholder="时间段" style="width: 120px;">
                    <el-option label="全部" value="" />
                    <el-option label="上午" value="上午" />
                    <el-option label="下午" value="下午" />
                </el-select>
                <el-button type="primary" @click="fetchDetailData" style="margin-left: 10px;">查询</el-button>
            </div>

            <el-table :data="detailData" border style="width: 100%; margin-top: 15px;" v-loading="detailLoading">
                <el-table-column prop="date" label="日期" width="110" />
                <el-table-column prop="timePeriod" label="时间段" width="80" />
                <el-table-column prop="className" label="班级" width="140" />
                <el-table-column prop="total" label="总人数" width="80" align="center" />
                <el-table-column prop="present" label="实到人数" width="90" align="center" />
                <el-table-column prop="absent" label="缺勤人数" width="90" align="center" />
                <el-table-column prop="attendanceRate" label="出勤率" width="80" align="center" />
                <el-table-column label="考勤详情" width="100">
                    <template #default="scope">
                        <el-button type="primary" size="small" link
                            @click="viewAttendanceDetail(scope.row)">查看</el-button>
                    </template>
                </el-table-column>
            </el-table>

            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>

        <!-- 考勤详情弹窗 -->
        <el-dialog v-model="attendanceDetailDialogVisible" title="考勤明细" width="50%" append-to-body>
            <el-table :data="attendanceDetailData" border v-loading="attendanceDetailLoading">
                <el-table-column prop="studentName" label="学生姓名" />
                <el-table-column prop="studentId" label="学号" />
                <el-table-column prop="status" label="考勤状态">
                    <template #default="scope">
                        <el-tag :type="scope.row.status === '正常' ? 'success' : 'danger'">
                            {{ scope.row.status }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="reason" label="缺勤原因" />
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="attendanceDetailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getClassList, getHistoryAttendance, getAttendanceDetail, exportAttendanceData } from '../../api/kaoqin'
import type { ClassItem, HistoryAttendanceItem, AttendanceDetailItem } from '../../api/kaoqin.d.ts'

const router = useRouter()
const route = useRoute()
const activeTab = ref('history')
const loading = ref(false)

// 监听路由变化高亮对应tab
watch(
    () => route.path,
    (path) => {
        if (path.includes('/main/attendance/manage')) {
            activeTab.value = 'today'
        } else if (path.includes('/main/attendance/absence')) {
            activeTab.value = 'absence'
        } else if (path.includes('/main/attendance/history')) {
            activeTab.value = 'history'
        } else if (path.includes('/main/attendance/leave')) {
            activeTab.value = 'leave'
        } else if (path.includes('/main/attendance/leaveSchool')) {
            activeTab.value = 'leaveSchool'
        } else if (path.includes('/main/attendance/setting')) {
            activeTab.value = 'setting'
        }
    },
    { immediate: true }
)

// tab点击时跳转到对应路由
function onTabClick(tab: any) {
    if (tab.paneName === 'today') {
        router.push('/main/attendance/manage')
    } else if (tab.paneName === 'absence') {
        router.push('/main/attendance/absence')
    } else if (tab.paneName === 'history') {
        router.push('/main/attendance/history')
    } else if (tab.paneName === 'leave') {
        router.push('/main/attendance/leave')
    } else if (tab.paneName === 'leaveSchool') {
        router.push('/main/attendance/leaveSchool')
    } else if (tab.paneName === 'setting') {
        router.push('/main/attendance/setting')
    }
}

const dateRange = ref(['2025-03-01', '2025-03-31'])
const className = ref('')
const classOptions = ref<string[]>([])

// 历史考勤统计数据
const tableData = ref([
    { id: '1', className: '一年级（1）班', attendanceDays: 30, totalAttendance: 1530, actualAttendance: 1521, absenceCount: 9, attendanceRate: '99.4%' },
    { id: '2', className: '一年级（2）班', attendanceDays: 30, totalAttendance: 1260, actualAttendance: 1255, absenceCount: 5, attendanceRate: '99.6%' },
])

// 历史考勤详情相关
const detailDialogVisible = ref(false)
const detailLoading = ref(false)
const detailData = ref<HistoryAttendanceItem[]>([])
const detailDate = ref('')
const detailTimePeriod = ref('')
const currentClassName = ref('')
const currentClassId = ref('')

// 考勤明细相关
const attendanceDetailDialogVisible = ref(false)
const attendanceDetailLoading = ref(false)
const attendanceDetailData = ref<AttendanceDetailItem[]>([])

// 获取班级列表
async function fetchClassList() {
    try {
        const response = await getClassList()
        if (response.data && response.data.code === 200) {
            classOptions.value = response.data.data.map((item: ClassItem) => item.className)
        } else {
            classOptions.value = ['一年级（1）班', '一年级（2）班']
        }
    } catch (error) {
        console.error('获取班级列表失败:', error)
        classOptions.value = ['一年级（1）班', '一年级（2）班']
    }
}

// 查询按钮点击
function handleQuery() {
    fetchHistoryData()
}

// 获取历史考勤数据
async function fetchHistoryData() {
    loading.value = true
    try {
        // 这里实际应该调用后端API获取历史考勤统计数据
        // 由于目前缺少这个专门的API，这里使用模拟数据
        await new Promise(resolve => setTimeout(resolve, 600))

        // 模拟按班级筛选
        if (className.value) {
            tableData.value = tableData.value.filter(item => item.className === className.value)
        } else {
            // 重置为所有班级数据
            tableData.value = [
                { id: '1', className: '一年级（1）班', attendanceDays: 30, totalAttendance: 1530, actualAttendance: 1521, absenceCount: 9, attendanceRate: '99.4%' },
                { id: '2', className: '一年级（2）班', attendanceDays: 30, totalAttendance: 1260, actualAttendance: 1255, absenceCount: 5, attendanceRate: '99.6%' }
            ]
        }

    } catch (error) {
        console.error('获取历史考勤数据失败:', error)
        ElMessage.error('获取历史考勤数据失败')
    } finally {
        loading.value = false
    }
}

// 重置按钮
function handleReset() {
    dateRange.value = ['2025-03-01', '2025-03-31']
    className.value = ''
    fetchHistoryData()
}

// 导出数据
async function handleExport() {
    try {
        const params = {
            startDate: dateRange.value ? dateRange.value[0] : '',
            endDate: dateRange.value ? dateRange.value[1] : '',
            className: className.value
        }

        const response = await exportAttendanceData(params)

        if (response.data && response.data.code === 200) {
            ElMessage.success('导出成功')
            // 实际项目中，这里应该处理文件下载
        } else {
            ElMessage.error('导出失败')
        }
    } catch (error) {
        console.error('导出数据失败:', error)
        ElMessage.error('导出数据失败')
    }
}

// 查看详情
function viewDetail(row: any) {
    detailDialogVisible.value = true
    currentClassName.value = row.className
    currentClassId.value = row.id
    detailDate.value = ''
    detailTimePeriod.value = ''
    fetchDetailData()
}

// 获取历史考勤详情数据
async function fetchDetailData() {
    detailLoading.value = true
    try {
        const params = {
            className: currentClassName.value,
            startDate: dateRange.value[0],
            endDate: dateRange.value[1],
            date: detailDate.value,
            timePeriod: detailTimePeriod.value
        }

        const response = await getHistoryAttendance(params)

        if (response.data && response.data.code === 200) {
            detailData.value = response.data.data
        } else {
            ElMessage.error('获取考勤详情失败')
            detailData.value = []
        }
    } catch (error) {
        console.error('获取考勤详情失败:', error)
        ElMessage.error('获取考勤详情失败')
        detailData.value = []
    } finally {
        detailLoading.value = false
    }
}

// 查看考勤明细
async function viewAttendanceDetail(row: HistoryAttendanceItem) {
    attendanceDetailDialogVisible.value = true
    attendanceDetailLoading.value = true

    try {
        const response = await getAttendanceDetail(row.id)

        if (response.data && response.data.code === 200) {
            attendanceDetailData.value = response.data.data
        } else {
            ElMessage.error('获取考勤明细失败')
            attendanceDetailData.value = []
        }
    } catch (error) {
        console.error('获取考勤明细失败:', error)
        ElMessage.error('获取考勤明细失败')
        attendanceDetailData.value = []
    } finally {
        attendanceDetailLoading.value = false
    }
}

// 组件挂载时获取数据
onMounted(() => {
    fetchClassList()
    fetchHistoryData()
})
</script>

<style scoped>
.history-attendance {
    background: #f7fafd;
    padding: 20px;
}

.filter-bar {
    margin: 20px 0 10px 0;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
}

.result-info {
    margin-bottom: 10px;
    color: #409eff;
}

.detail-filter {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
}
</style>